package com.shqcjd.preinstallmobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.DefectManageTypeBean;
import com.shqcjd.preinstallmobile.model.pojo.InspectionRecordBean;
import com.shqcjd.preinstallmobile.ui.adapter.InspectRecordAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.WrapContentLinearLayoutManager;
import com.shqcjd.preinstallmobile.widget.DateDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class InspectRecordActivity extends BaseActivity {
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.btn_inspect_record_time)
    Button btnInspectRecordTime;
    @BindView(R.id.sp_inspect_record_people)
    Spinner spInspectRecordPeople;
    @BindView(R.id.rv_inspect_record)
    RecyclerView rv_inspect_record;
    @BindView(R.id.sr_inspect_record)
    SwipeRefreshLayout srInspectRecord;

    private Context context;
    private int uId;
    private InspectRecordAdapter inspectRecordAdapter;
    private List<InspectionRecordBean.ListBean> mList = new ArrayList<>();
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    List peopleList = new ArrayList<String>();
    List<DefectManageTypeBean> tList = new ArrayList<>();
    private int typeId;
    private DateDialog dateDialog;
    private String bTime = "", eTime = "";
    private int eId;
    private String kks;
    private int total;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_inspect_record;
    }

    @Override
    public void init() {
        super.init();
        eId = getIntent().getIntExtra("eId", -1);
        kks = getIntent().getStringExtra("kks");
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        tvIncludeTitle.setText("巡检记录");

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        srInspectRecord.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        spInspectRecordPeople.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0)
                    return;
                if(position==1){
                    typeId = 0;
                }else if(position>1){
                    typeId = tList.get(getListValue(peopleList.get(position)+"")).value;
                }
                uId = typeId;
                refreshData();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btnInspectRecordTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dateDialog == null) {
                    dateDialog = new DateDialog(context);
                    dateDialog.setOnCheckDate(new DateDialog.setOnCheckDateListener() {
                        @Override
                        public void onCheckDate(String time, String endTime) {
                            bTime = time;
                            eTime = endTime;
                            btnInspectRecordTime.setText(bTime+"-"+eTime+" ▾");
                            refreshData();
                        }
                    });
                }
                dateDialog.show();
            }
        });

        refreshData();
        getUserData();
    }

    private void refreshData() {
        refreshOrLoadMore();
        srInspectRecord.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        mList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }
    private void refreshOrLoadMore(){
        if(inspectRecordAdapter!=null){
            inspectRecordAdapter.notifyLoadMoreToLoading();
        }
    }

    private int getListValue(String str){
        for(int i=0; i<tList.size(); i++){
            if(str.equals(tList.get(i).label)){
                return i;
            }
        }
        return 0;
    }


    private void getUserData() {
        ApiService.getInspectionUser()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<DefectManageTypeBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<DefectManageTypeBean>> responseData) {
                        if(responseData.retCode!=10000){
                            return;
                        }
                        tList = responseData.data;
                        peopleList.add("巡检人员 ▾");
                        peopleList.add("全部");
                        for(int i=0; i<responseData.data.size(); i++){
                            peopleList.add(responseData.data.get(i).label);
                        }
                        ArrayAdapter peopleAdapter = new ArrayAdapter<String>(context, R.layout.item_spinner_inspect, peopleList);
                        peopleAdapter.setDropDownViewResource(R.layout.item_spinner_inspect);
                        spInspectRecordPeople.setAdapter(peopleAdapter);
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srInspectRecord.setRefreshing(false);
                    }
                });
    }

    private void getData(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", p+"");
        map.put("pageSize", "16");
        map.put("user_id", uId+"");//巡检人id
        map.put("start_time", bTime);
        map.put("end_time", eTime);
        map.put("equipmentId", eId+"");
        ApiService.inspectRecordHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<InspectionRecordBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<InspectionRecordBean> responseData) {
                        if(responseData.retCode!=10000){
                            return;
                        }
                        total = responseData.data.total;
                        mList.addAll(responseData.data.list);
                        if (inspectRecordAdapter == null) {
                            rv_inspect_record.setLayoutManager(new WrapContentLinearLayoutManager(context));
                            inspectRecordAdapter = new InspectRecordAdapter(mList);
                            rv_inspect_record.setAdapter(inspectRecordAdapter);
                            inspectRecordAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    InspectionRecordBean.ListBean item = (InspectionRecordBean.ListBean) adapter.getItem(position);
                                    Intent intent = new Intent(InspectRecordActivity.this, EquipmentInspectionRecordActivity.class);
                                    intent.putExtra("tId",item.id);
                                    intent.putExtra("kks",kks);
                                    startActivity(intent);
                                }
                            });
                            inspectRecordAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                @Override
                                public void onLoadMoreRequested() {
                                    rv_inspect_record.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            int pageSize = total%16==0?total/16:total/16+1;
                                            if (page >= pageSize) {
                                                inspectRecordAdapter.loadMoreEnd();
                                            } else {
                                                loadMoreData();
                                            }
                                        }
                                    });
                                }
                            });
                        }
                        if (isRefreshOrLoadMore == 1) {
                            page = page + 1;
                            inspectRecordAdapter.loadMoreComplete();
                        }
                        inspectRecordAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srInspectRecord.setRefreshing(false);
                    }
                });
    }

}
